package de.sonnentempel.dao;

import javax.persistence.EntityManager;

import de.sonnentempel.framework.JPAUtil;


class DAOHelper {

	private Class clazz;
	public DAOHelper(Class c)
	{
		clazz = c;
	}
	
	protected void deleteById(Object o) throws Exception {
		EntityManager em = null;
		try {
			em = JPAUtil.getEntityManager();
			em.getTransaction().begin();
			em.remove(o);
			em.getTransaction().commit();
		} catch (Exception e) {
			if (em.getTransaction().isActive()) {
				em.getTransaction().rollback();
			}
			throw new Exception("Fehler beim löschen", e);
		}
		finally
		{
			if (em != null)
			{
				em.close();
			}
		}
	}
	protected Object getById(Long id) throws Exception {
		EntityManager em = JPAUtil.getEntityManager();
		Object ret = (Object)em.find(clazz, id);
		em.close();
		return ret;
	}

	protected Object save(Object o) throws Exception {
		EntityManager em = JPAUtil.getEntityManager();
		try {
			em.getTransaction().begin();
			em.persist(o);
			em.getTransaction().commit();
		} catch (Exception e) {
			if (em.getTransaction().isActive()) {
				em.getTransaction().rollback();
			}
			throw new Exception("Fehler beim speichern", e);
		} finally {
			if (em != null) {
				em.close();
			}
		}
		return o;
	}
	
	protected Object update(Object o) throws Exception {
		EntityManager em = JPAUtil.getEntityManager();
		try {
			em.getTransaction().begin();
			em.merge(o);
			em.getTransaction().commit();
		} catch (Exception e) {
//			e.printStackTrace();
			if (em.getTransaction().isActive()) {
				em.getTransaction().rollback();
			}
			throw new Exception("Fehler beim aktualisieren", e);
		} finally {
			if (em != null) {
				em.close();
			}
		}
		return o;
	}
}
